import pay from '@/api/pay'

// 关于购物车已选择商品selectedGoodsId数组：因结算页存在微信登录重新刷新现象
// 所以不可以按rootState.cart.selectedGoodsId.toString()这样直接从cart.js直接读取
// 必须存一份到localStorage
// 切记：点击付款后必须清空localStorage的selectedGoodsId
const state = {
    selectedGoodsId: '',
    lastSelectedGoodsId: '',
    goodsInfo: {},
    addressInfo: {},
    postage: 0,
    bonus: 0,
    netPrice: 0,
    requestSend: false
}

const getters = {
    goodsInfo: state => state.goodsInfo,
    addressInfo: state => state.addressInfo,
    postage: state => state.postage,
    bonus: state => state.bonus,
    totalPrice: state => Number(state.netPrice) + Number(state.postage)
}

const actions = {
    async toSettleCartGoods ({state, dispatch, commit, rootState}) {
        // 判断是否有待结算商品
        if (!localStorage.getItem('selectedGoodsId')) return false
        // 根据selectedGoodsId是否改变来决定是否再需请求结算接口的 即改变地址后不会再请求一次结算接口
        if (state.lastSelectedGoodsId != localStorage.getItem('selectedGoodsId')) {
            commit('getSelectedGoodsId')
            const {data, success} = await pay.settleCartGoods(state.selectedGoodsId)
            commit('setInfo', {
                addressInfo: data.address_info,
                goodsInfo: data.goods_info,
                bonus: data.bonus,
                netPrice: data.sum_price
            })
        }
        await dispatch('getPostage')
        return true
    },
    // 原来我是在这里做的地址选择的处理…我自己都要不记得了…
    async getPostage ({state, commit, rootState}) {
        const sA = rootState.address.list.find(a => a.address_id == rootState.address.selected)
        const addressInfo = sA ? {
            address_id: sA.address_id,
            address: sA.receive_province + sA.receive_city + sA.receive_area,
            receive_name: sA.receive_name,
            receive_mobile: sA.receive_mobile
        } : state.addressInfo
        commit('setAddress', addressInfo)
        const {data, success} = await pay.getPostage({
            selectedGoodsId: state.selectedGoodsId,
            addressId:　addressInfo.address_id
        })
        commit('setPostage', data.postage)
    },
    // 生成订单
    async submitOrder ({state, commit, rootState}, {note,type}) {
        const submitOrderRes = await pay.submitOrder({
            address_id: state.addressInfo.address_id,
            goods_id: state.selectedGoodsId,
            user_id: rootState.user.userInfo.user_id,
            type,
            note
        })
        // 清空本地的待结算商品
        localStorage.removeItem('selectedGoodsId')
        // 返回的是orderId
        return submitOrderRes.data.order_id
    },
    // 支付
    async payOrder ({state, commit, rootState}, {router, orderFormLogId, orderId, type}) {
        const { success, data, msg } = type == 1
            ? await pay.getCharge({
                type,
                orderFormLogId,
                totalPrice: state.netPrice + state.postage,
                userId: rootState.user.userInfo.user_id
            }) : await pay.getCharge({
                type,
                orderId,
                totalPrice: state.netPrice + state.postage,
                userId: rootState.user.userInfo.user_id
            })
        if (!success) return {success, msg}
        const charge = data.charge
        try {
            await pay.WxPay(charge)
            // 注意router是要传过来的router喔
            router.replace(`/order/paySuccess/id?type=${type}`)
        } catch (err) {
            router.replace('/order/list?type=2')
        }
        return { success: true }
    }
}

const mutations = {
    getSelectedGoodsId (state) {
        console.log('需结算goodsId: ' + localStorage.getItem('selectedGoodsId'))
        state.selectedGoodsId = state.lastSelectedGoodsId = localStorage.getItem('selectedGoodsId')
    },
    setInfo (state, {addressInfo, goodsInfo, bonus, netPrice}) {
        state.addressInfo = addressInfo
        state.goodsInfo = goodsInfo
        state.bonus = bonus
        state.netPrice = netPrice
    },
    setPostage (state, postage) {
        state.postage = postage
    },
    setAddress (state, addressInfo) {
        state.addressInfo = addressInfo
    },
    requestSend (state) {
        state.requestSend = true
    }
}

export default {
    state,
    getters,
    actions,
    mutations,
    namespaced: true
}
